package com.crr.servlet;

import com.crr.dao.UserDao;
import com.crr.dao.impl.UserDaoImpl;
import com.crr.entity.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserDao ud = new UserDaoImpl();
        User u = ud.userLogin(username, password);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if (u != null) {
//            将user对象信息存入session作用域
            req.getSession().setAttribute("u",u);
//        采用cookie的方式存储
//            Cookie cUser = new Cookie("name", u.getUserName());
//            cUser.setMaxAge(60 * 60);
//            resp.addCookie(cUser);
            out.println("<script> alert('登录成功'); location.href='main.jsp'</script>");

        } else {
            out.println("<script> alert('登录失败'); location.href='userlogin.html'</script>");
        }
    }
}
